

var splitLevel = "............................................";
function dataViewOnPastNode(args) {
    var selectedCell = grid.getActiveCell();
    if (selectedCell) {
        var startRow = selectedCell.row;
        var rowData = grid.getDataItem(startRow);
        var children = [];
        rowData.___path = "";
        var treeViewStack = [rowData];
        var bomValidator = {
            parentPath: function (row, rows) {
                var tempRow = row;
                var parentPath = [];
                while (tempRow) {
                    parentPath.unshift(grid.rowKey(tempRow));
                    if (tempRow.parent) {
                        tempRow = grid.findItemById(tempRow.parent);
                    } else {
                        tempRow = null;
                    }
                }
                return parentPath;
            }
        }

        // 20210722
        // samenode , then fullParentPath
        // checkAllSubs , check current page only , service check others
        var parentPath = [];
        dataViewAllSameNode(rowData, (s) => {
            var tPath = bomValidator.parentPath(s, grid.getSourceData());
            for (var i = 0; i < tPath.length; i++) {
                if (parentPath.indexOf(tPath[i]) < 0) {
                    parentPath.push(tPath[i]);
                }
            }
        });

        var tempParentPath = [].concat(parentPath);

        // 获取当前件的父路径
        var parentPath = bomValidator.parentPath(rowData, grid.getSourceData());

        var realCols = [];
        for (var i = 0; i < grid.getColumns().length; i++) {
            if (grid.getOptions().exportIgnoreCols.indexOf(grid.getColumns()[i].id) <= 0) {
                realCols.push(grid.getColumns()[i]);
            }
        }

        for (var x = 0; x < args.length; x++) {

            // 创建新的对象
            var nRow = {};
            nRow.id = Tl.id();
            if (rowData.children == undefined) {
                rowData.children = [];
            }

            var startCell = 1;
            // export ignoreColmns
            if (args[x].length > 1) {
                for (var y = startCell; y < args[x].length; y++) {
                    if (y < realCols.length) {
                        grid.dataColumnValueSetter(nRow, realCols[y - 1], args[x][y]);
                    }
                }
            } else {
                grid.dataColumnValueSetter(nRow, realCols[0], args[x][0]);
            }

            nRow.__state = 0;
            nRow.___path = args[x][0] ? splitLevel.substring(0, args[x][0].split(".").length) : ".";

            // 获取新增的，即不在合同上存在的
            // 获取差异的，如果在合同上的，子直接用合同上的数据进行替换（从上到下，仍需要验证死循环）
            // 获取正常的

            if (treeViewStack.length > 0) {
                if (treeViewStack[treeViewStack.length - 1].___path.length < nRow.___path.length) {

                    var parent = treeViewStack[treeViewStack.length - 1];
                    // 找到父
                    var nParentPath = treeViewStack.filter((v) => {
                        return grid.rowKey(v) === grid.rowKey(nRow);
                    });

                    if (nParentPath.length > 0 || parentPath.indexOf(grid.rowKey(nRow)) != -1) {
                        parentPath.push(grid.rowKey(nRow));
                        sbz.Msg.alert("死循环:" + parentPath);
                        return;
                    }

                    treeViewStack.push(nRow);

                    // 确定层级
                    dataViewPath(parent, nRow, parent.children.length + 1);
                } else {
                    // 找到最近的兄弟或直接的父
                    var tempPaths = [];
                    tempPaths.push(parentPath);
                    for (var i = treeViewStack.length - 1; i >= 0; i--) {
                        if (treeViewStack[i].___path.length >= nRow.___path.length) {
                            treeViewStack.pop();
                        } else {
                            tempPaths.push(grid.rowKey(treeViewStack[i]));
                        }
                    }

                    if (tempPaths.indexOf(grid.rowKey(nRow)) != -1) {
                        sbz.Msg.alert("死循环:" + parentPath);
                        return;
                    }

                    var parent = treeViewStack[treeViewStack.length - 1];
                    if (parent.children === undefined) {
                        parent.children = [];
                    }

                    treeViewStack.push(nRow);
                    // 确定层级
                    dataViewPath(parent, nRow, parent.children.length + 1);
                }
            }
            // 提示是否增加 行 ，假设增加
            // 直接更新和刷新状态...
            children[x] = nRow;
        }

        isRecycle = false;
        recyclePaths = [];
        checkRecyle(rowData, children, tempParentPath);

        if (!isRecycle) {
            treeViewInsertItem(rowData, children);
        } else {
            var recycleMsg = "循环：<br/>";
            for (var i = 0; i < recyclePaths.length; i++) {
                recycleMsg += "<br/>";
                recycleMsg += recyclePaths[i].join("->");
            }
            alert(recycleMsg);
        }

        isRecycle = false;

    }
    return true;
}

function checkRecyle(node, children, fullPath) {
    if (children && children.length > 0) {
        var nRows = [];
        var sParent = [];
        sParent = node;
        var subs = children.filter(s => { return grid.equalRow(s, node); });
        for (var j = 0; j < subs.length; j++) {
            // 判断原父是否存在，如果存在，此时需要将整体的子进行删除并增加原来的逻辑
            var nSub = $.extend({}, subs[j]);
            nSub.id = Tl.id();
            dataViewCreateNewNodes(children, nSub, node, nRows, subs[j], fullPath);
        }
    }
}

function dataViewAllSameNode(item, each) {
    var res = grid.getSourceData().filter((v) => {
        return grid.rowKey(item, v);
    });

    if (each) {
        for (var i = 0; i < res.length; i++) {
            each(res[i], i);
        }
    }
    return res;
}

var isRecycle = false;
var recyclePaths = [];
function dataViewCopyNewNodes(sSubs, sParent, nRow, nRows, fullPath) {
    var subs = sSubs.filter(s => s.parent == sParent.id);
    for (var j = 0; j < subs.length; j++) {
        var nSub = $.extend({}, subs[j]);
        if (fullPath && fullPath.indexOf(rowKey(nSub)) > 0) {
            isRecycle = true;
            var tPath = [].concat(fullPath);
            tPath.push(rowKey(nSub));
            recyclePaths[recyclePaths.length] = tPath;
            break;
        }

        var sFullPath = undefined;
        if (fullPath) {
            var sFullPath = [].concat(fullPath);
            sFullPath.push(rowKey(nSub));
        }


        nSub.id = Tl.id();
        nSub.children = [];

        dataViewPath(nRow, nSub, nRow.children.length);
        nRow.children.push(nSub);
        nRows.push(nSub);

        dataViewCopyNewNodes(sSubs, subs[j], nSub, nRows, sFullPath);
    }
}


function treeViewInsertItem(item, children) {
    if (children && children.length > 0) {
        var nRows = [];
        var sParent = [];
        dataViewAllSameNode(item, function (node, ix) {
            if (ix == 0) {
                sParent = node;
                var subs = children.filter(s => grid.rowKey(s) == grid.rowKey(node));
                for (var j = 0; j < subs.length; j++) {
                    // 判断原父是否存在，如果存在，此时需要将整体的子进行删除并增加原来的逻辑
                    var nSub = $.extend({}, subs[j]);
                    nSub.id = sbz.uuid();
                    createNodes(children, nSub, node, nRows, subs[j]);
                }
                Tl.Arrays.insert(grid.getSourceData(), node, nRows);
            } else {
                var copyRows = [];
                dataViewCopyNewNodes(nRows, sParent, node, copyRows);
                Tl.Arrays.insert(grid.getSourceData(), node, copyRows);
            }
        });
        refresh();
    }
}


function dataViewCreateNewNodes(rows, nRow, parent, nRows, src, fullPath) {
    dataViewPath(parent, nRow, parent.children.length);
    parent.children.push(nRow);
    nRows.push(nRow);
    var sFullPath = undefined;
    // 判断，确认子逻辑
    var matchs = dataViewAllSameNode(nRow);
    if (matchs.length > 0) {
        // 拷贝所有子
        var sParent = matchs[0];
        var sSubs = grid.findSubItemsById(sParent.id);
        if (fullPath) {
            sFullPath = [].concat(fullPath);
        }
        dataViewCopyNewNodes(sSubs, sParent, nRow, nRows, sFullPath);
        return;
    } else {
        // 继续新增
        var subs = rows.filter(item => item.parent == src.id);
        for (var i = 0; i < subs.length; i++) {
            var nSub = $.extend({}, subs[i]);
            nSub.id = sbz.uuid();
            if (fullPath) {
                sFullPath = [].concat(fullPath);
            }
            dataViewCreateNewNodes(rows, nSub, nRow, nRows, subs[i], fullPath);
        }
    }
}

function dataViewPath(parentNode, data, index) {
    if (parentNode) {
        data.__path = parentNode.__path + "." + (index + 1);
        data.__index = index;
        data.parent = parentNode.id;
        data.indent = parentNode.indent + 1;
        data.parentNode = parentNode;
    } else {
        data.__path = "1";
        data.indent = 1;
        data.__index = index;
    }
}


function getMaxOrderId(parent, current) {
    if (!parent || !parent.children || !current || !current.data || !current.data.bom) {
        return 1;
    }

    var maxOrderId = current.data.bom.orderId ? current.data.bom.orderId : 0;
    // 获取最大orderId 20210911
    for (var i = 0; i < parent.children.length; i++) {
        var sibling = parent.children[i];
        maxOrderId = maxOrderId > i ? maxOrderId : i;
        if (sibling && sibling.data && sibling.data.bom && sibling.data.bom.orderId) {
            maxOrderId = maxOrderId > sibling.data.bom.orderId ? maxOrderId : sibling.data.bom.orderId;
        }
    }

    current.data.bom.orderId = maxOrderId + 1;
}


function refresh() {
    dataView.beginUpdate();
    dataView.setItems(grid.getSourceData());
    dataView.setFilter(myFilter);
    dataView.endUpdate();
    grid.invalidate();
}